﻿using System;
using AllInOnePluginBL.jobs;
using NLog;

namespace AllInOnePluginBL.Helpers
{
    /// <summary>
    /// Summary description for PluginHandler
    /// </summary>
    public class PluginHandler
    {
        private readonly Logger _log = LogManager.GetLogger("PluginHandler");
        private JobsScheduler _schedler;

        /// <summary>
        /// This routine creates a background worker and starts it working on another thread to 
        /// periodically refresh this applications cached data as needed.
        /// </summary>
        public void StartScheduler()
        {
            if (_schedler != null) return;

            #region Scheduler Setup
            _log.Info("------- Start Initializing jobs schduler ----------------------");

            // construct a scheduler factory
            _schedler = new JobsScheduler();
            
            _log.Info("------- End Initializing jobs schduler ----------------------");

            InitializeSiteParsersjobs();
            _log.Info("------- End InitializeSiteParsersjobs -----------------");

            _schedler.Start();
            _log.Info("------- Started Scheduler -----------------");
            #endregion
        }

        public void StopScheduler()
        {
            _log.Info("------- Stop Scheduler ---------------------");
            _schedler.Stop();
            _log.Info("------- Stop Complete -----------------");
        }

        private void InitializeSiteParsersjobs()
        {
            var pluginDBHandler = PluginDBHandler.Instance;
            var jobsTypesList = pluginDBHandler.GetJobsTypesList();

            foreach (var jobsType in jobsTypesList)
            {
                var currentTime = DateTime.Now;

                _log.Info("[Job:{0}] [currentTime:{1}] [LastRunTime:{2}]", jobsType.Name, currentTime, jobsType.LastRunTime);
                
                var nextRunTime = jobsType.LastRunTime.AddHours(jobsType.RunTimeIntervalInHOUR);
                var runTriggerNow = nextRunTime.CompareTo(currentTime) != 1;

                if (runTriggerNow)
                {
                    nextRunTime = currentTime.AddHours(-jobsType.RunTimeIntervalInHOUR).AddSeconds(30);
                }
                else
                {
                    var dateDiff = nextRunTime.Subtract(currentTime);
                    nextRunTime = currentTime + dateDiff;
                }

                _schedler.AddJob(jobsType.Name, Type.GetType(jobsType.ClassName), nextRunTime, new TimeSpan((int)jobsType.RunTimeIntervalInHOUR, 0, 0));
                _log.Info("{0} will run at: {1}", jobsType.Name, nextRunTime.AddHours(jobsType.RunTimeIntervalInHOUR).ToString("r"));
            }
        }
    }
}